package com.dobbinsoft.iotechn.device.mqtt.handler;

import com.dobbinsoft.iotechn.data.compent.CacheComponent;
import com.dobbinsoft.iotechn.device.constant.DeviceConst;
import com.dobbinsoft.iotechn.device.domain.DeviceDO;
import com.dobbinsoft.iotechn.device.domain.DeviceLogDO;
import com.dobbinsoft.iotechn.device.enums.DeviceLevelType;
import com.dobbinsoft.iotechn.device.enums.IotMessageResultType;
import com.dobbinsoft.iotechn.device.enums.IotMessageType;
import com.dobbinsoft.iotechn.device.mapper.DeviceLogMapper;
import com.dobbinsoft.iotechn.device.mqtt.message.IotDeviceLogMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * Description:
 * User: rize
 * Date: 2020/6/27
 * Time: 13:42
 */
public class IotMqttLogMessageHandler implements IotMqttMessageHandler<IotDeviceLogMessage> {

    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private DeviceLogMapper deviceLogMapper;

    @Override
    public int handle(String accessKeyId, IotDeviceLogMessage msg) {
        if (!DeviceLevelType.contains(msg.getCode())) {
            return IotMessageResultType.SUCCESS.getCode();
        }
        DeviceDO deviceDO = cacheComponent.getHashObj(DeviceConst.CA_DEVICE_HASH, accessKeyId, DeviceDO.class);
        if (deviceDO != null) {
            DeviceLogDO deviceLogDO = new DeviceLogDO();
            deviceLogDO.setDeviceId(deviceDO.getId());
            deviceLogDO.setLevel(msg.getLevel());
            deviceLogDO.setLog(msg.getLog());
            deviceLogDO.setGmtCreate(new Date());
            deviceLogMapper.insert(deviceLogDO);
        }
        return IotMessageResultType.SUCCESS.getCode();
    }

    @Override
    public int getCode() {
        return IotMessageType.DEVICE_LOG.getCode();
    }

    @Override
    public Class<IotDeviceLogMessage> getMessageType() {
        return IotDeviceLogMessage.class;
    }
}
